package fox.framework.rpc.client.invocation;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @author cuichao
 * @Description: ConsumeInvokerChain
 * @Date: create in 2021/1/15 21:56
 */
public abstract class ConsumeInvokerChain {

    private List<ConsumeInvoker> chains;
    private int currentIndex = -1;

    public ConsumeInvokerChain(){
        super();
    }

    public ConsumeInvokerChain(List<ConsumeInvoker> chains) {
        this.chains = chains;
    }


    /**
     * 执行调用链
     * @return
     * @throws Throwable
     */
    public Object doChain(Object proxy, Method method, Object[] args) throws Throwable {
        if (chains == null || currentIndex == chains.size() - 1) {
            return invoke(proxy, method ,args);
        } else {
            return chains.get(++currentIndex).doInvoke(this, method ,args);
        }
    }

    /**
     * 过滤器链最终执行方法
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    protected abstract Object invoke(Object proxy, Method method, Object[] args) throws Throwable;


    public void setChains(List<ConsumeInvoker> chains) {
        this.chains = chains;
    }
}
